<?php

class Admin_ResultadosimuladoController extends App_Controller_Action
{

    private $_table     = 'PUBLICACAO_SIMULADO';
    private $_pk        = 'PLS_ID';
    private $_order_col = 'PLS_DATENC DESC, PLS_HORENC DESC, PLS_ID';
    private $_order     = 'DESC';
    private $_sta_col   = 'PLS_STA';
    private $obj        = '';
    private $form       = '';
    
    private $_PER_ID;
    private $_USU_ID;
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Resultadosimulado();
        
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        $this->_PER_ID = $s_user->read()->PER_ID;
        $this->_USU_ID = $s_user->read()->USU_ID;
    }
 
    public function indexAction() {
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('elemform','library');
        Zend_Loader::loadClass('dominio','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
         
        $where = $this->_pk . ' > 0';
        
        
        $stafiltro = $this->_getParam('stafiltro', '1,2');      
        if($stafiltro != '') $where .= ' and PLS_STA in(' . $stafiltro.')';    
        $this->view->stafiltro = $stafiltro;
        
        //if($this->_PER_ID <> 1) $where .= ' AND USU_ID = '.$this->_USU_ID;
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    public function editAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('formula','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_publicacaolista.js');
        
        
        $this->view->form = $this->form;
        if($this->getRequest()->isPost()) { 
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $data = $formData;//$this->form->getValues(); 
                    
                    unset($data['Salvar']);
                    unset($data['destino']);
                    
                    $this->db->beginTransaction();
                    if($id == 0){ 
                    
                        
                    }
                    else{
                        
                        $id = $this->_getParam('id', 0);
                        if ($id > 0) {
                            $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
                            $pub = $this->db->fetchRow($query);
                        }
                        
                        if($data['PLS_STAALU']){
                            
                            $data['PLS_DATRES'] = date('Y-m-d');
                            $data['PLS_HORRES'] = date('H:i:s');
                            $data['PLS_STA'] = 2;
                            
                            $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                            
                            // lista
                            $query = 'SELECT SQL_CACHE p.FAP_FORINS FROM LISTA_SIMULADO l, FACULDADE_PROVA p '
                                        .' WHERE l.FAC_ID = p.FAC_ID AND l.FAP_ID = p.FAP_ID '
                                        .' AND LTS_ID = ' . $pub['LTS_ID'];
                            $lista = $this->db->fetchRow($query);
                            
                            // alunos
                            $query = 'SELECT SQL_CACHE a.*,p.PLS_REDID, p.PLS_REDNQU, p.PLS_REDPES '
                                    .' FROM PUBLICACAO_SIMULADO_ALUNO a, PUBLICACAO_SIMULADO p '
                                    .' WHERE a.PLS_ID = p.PLS_ID '
                                    .' AND a.'.$this->_pk.' = ' . $id.' AND p.'.$this->_pk.' = ' . $id;
                            $result = $this->db->fetchAll($query);
                            foreach($result as $alu){
                                
                                // aluno
                                $tot = 0;
                                $qtd_acerto = 0;
                                
                                // por disciplana
                                $n_dis_total = 0;
                                $f_arr = array();
                                $query = ' SELECT SQL_CACHE * FROM PUBLICACAO_SIMULADO_GABARITO '
                                        .' WHERE '.$this->_pk.' = ' . $id
                                        .' GROUP BY DCP_ID'
                                        .' ORDER BY PSG_QST';
                                $diss = $this->db->fetchAll($query);
                                foreach($diss as $dis){
                                    
                                    // teste para mostra ou não questão de lingua estrangeira selecionada
                                    $lngetg_qst = true;
                                    if($dis['PSG_STALNGETG'] == 1){
                                        if($dis['DCP_ID'] == $alu['DCP_ID']) $lngetg_qst = true;
                                        else $lngetg_qst = false;
                                    } 

                                    if($lngetg_qst){
                                        
                                        $n_dis_total++;
                                        $n_acertos = 0;
                                        $n_total = 0;
                                        
                                        /*
                                        // totalizador de questoes
                                        $query = 'SELECT count(*) as TOTAL ' 
                                                .' FROM PUBLICACAO_SIMULADO_GABARITO '
                                                .' WHERE PLS_ID = '.$id.' AND DCP_ID = '.$dis['DCP_ID']
                                                .' GROUP BY DCP_ID';
                                        $row_tot = $this->db->fetchRow($query);
                                        $tot += $row_tot['TOTAL'];
                                        */
                                        
                                        $query = 'SELECT SQL_CACHE p.*, r.* '
                                                . 'FROM PUBLICACAO_SIMULADO_GABARITO p, PUBLICACAO_SIMULADO_RESPOSTA r '
                                                .' WHERE p.PLS_ID = r.PLS_ID AND p.PSG_ID = r.PSG_ID'
                                                .' AND p.PLS_ID = '.$id.' AND r.PLS_ID = '.$id
                                                .' AND r.ALU_ID = '.$alu['ALU_ID']
                                                .' AND p.DCP_ID = r.DCP_ID '
                                                .' AND p.DCP_ID = '.$dis['DCP_ID'].' AND r.DCP_ID = '.$dis['DCP_ID']
                                                .' ORDER BY p.PSG_QST';
                                        $ress = $this->db->fetchAll($query);
                                        foreach($ress as $res){
                                            $tot++; // totalizador de questoes respondidas
                                            $n_total++;

                                            if($res['PSG_ALT'] == $res['PSR_ALT'] ){
                                                $n_acertos++; // echo ' Acertou';
                                                $qtd_acerto++;
                                            } 

                                        }
   
                                        $NA = $n_acertos;
                                        $NQ = $n_total;
                                        $P = $dis['PSG_PES'];
      
                                        $f_arr[] = array('NA' => $NA,'NQ' => $NQ,'P' => $P);
                                    
                                    
                                        // RELATORIO - resultado por disciplana
                                        $ins = array(
                                            'PLS_ID'    => $id,
                                            'DCP_ID'    => $dis['DCP_ID'],
                                            'ALU_ID'   => $alu['ALU_ID'],
                                            'PQD_POR'   => tools::trunc_valor(($n_acertos * 100) / $n_total),
                                            'PQD_TOT'   => $n_total,
                                            'PQD_ACR'   => $n_acertos,
                                        );
                                        try { $this->db->insert('PUBSIM_DISALU', $ins); } catch (Exception $ex) { }
                                        // FIM RELATORIO
                                    } 
                                }
                                
                                $PLA_REDID = 0;
                                $PLA_REDNTA = 0;
                                $PLA_REDPSO = 0;
                                $PLA_REDNTAPSO = 0;
                                // nota redação do aluno
                                if($alu['PLS_REDID'] > 0){
                                    $NA =  $alu['PSA_REDNTA'] * ($alu['PLS_REDNQU'] / 10); // nota * ( nº questões / 10) . Nota vai ate 10
                                    $NQ = $alu['PLS_REDNQU'];
                                    $P = $alu['PLS_REDPES'];

                                    $f_arr[] = array('NA' => $NA,'NQ' => $NQ,'P' => $P);
                                    
                                    $PLA_REDID = $alu['PLS_REDID'];
                                    $PLA_REDNTA = $alu['PSA_REDNTA'];
                                    $PLA_REDPSO = $P;
                                    $PLA_REDNTAPSO = $NA;
                                }
                                
                                $resultado = formula::executarFormula($lista['FAP_FORINS'],$f_arr);
                                
                                // RELATORIO - resultado por aluno
                                $ins = array(
                                    'PLS_ID'    => $id,
                                    'ALU_ID'    => $alu['ALU_ID'],
                                    'PLA_POR'   => $resultado,
                                    'PLA_TOT'   => $tot,
                                    'PLA_ACR'   => $qtd_acerto,
                                    'PLA_REDID' => $PLA_REDID,
                                    'PLA_REDNTA' => $PLA_REDNTA,
                                    'PLA_REDPSO' => $PLA_REDPSO,
                                    'PLA_REDNTAPSO'=> $PLA_REDNTAPSO,
                                );
                                try { $this->db->insert('PUBSIM_RANALU', $ins); } catch (Exception $ex) { }
                                // FIM RELATORIO
                            }
                            
                             // rank alunos
                            $query = 'SELECT SQL_CACHE PLS_ID,ALU_ID  ' 
                                    .' FROM PUBSIM_RANALU '
                                    .' WHERE PLS_ID = '.$id
                                    .' ORDER BY PLA_ACR DESC, ALU_ID, PLS_ID';
                            $result2 = $this->db->fetchAll($query);
                            foreach($result2 as $key => $row2){
                                $this->db->update('PUBSIM_RANALU', array('PLA_POS' => ($key + 1)), 'PLS_ID = '.$id.' AND ALU_ID = '.$row2['ALU_ID']);
                            }
                            
                        }
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script> alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
                $data = $this->db->fetchRow($query);
                $data['PLS_DATENC'] = Datetools::amd_dma($data['PLS_DATENC']);
                $this->form->populate($data);
                $this->view->data = $data;
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                
                $ok = (bool) $this->db->delete('PUBLICACAO_SIMULADO_RESPOSTA', $this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete('PUBLICACAO_SIMULADO_ALUNO', $this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete('PUBLICACAO_SIMULADO_GABARITO', $this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }             
        }       
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
        //$this->_helper->redirector('index');
    }
    
    public function validaPubAluno($id,$aluno) {
        
        $query = 'SELECT SQL_CACHE ALU_ID FROM PUBLICACAO_SIMULADO_ALUNO WHERE PLS_ID = '.$id.' AND ALU_ID = '.$aluno;
        $row = $this->db->fetchRow($query);
        if($row['ALU_ID'] > 0 ) return false;
        else return true;
        
    }
   
}